package com.suo.enroll.utils;

import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class OpenAIUtil {

    private static final String OPENAI_API_KEY = "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";  // 使用环境变量
    private static final String OPENAI_API_URL = "http://7706ee4b4b518b432ac70ce9cad3f63f.api-forwards.com/v1/chat/completions";  // 使用HTTPS

    // 向 OpenAI API 发送请求
    public static String getOpenAIResponse(String text, String prompt) throws IOException {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(RequestConfig.custom()
                        .build())
                .build();

        HttpPost postRequest = new HttpPost(OPENAI_API_URL);

        // 设置请求头
        postRequest.setHeader("Content-Type", "application/json");
        postRequest.setHeader("Authorization", "Bearer " + OPENAI_API_KEY);

        // 构建请求体
        JSONObject json = new JSONObject();
        json.put("model", "gpt-4o");  // 修正模型名称
        json.put("temperature", 0.7);

        // 消息历史
        JSONObject systemMessage = new JSONObject();
        systemMessage.put("role", "system");
        systemMessage.put("content", "You are a helpful assistant.");

        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user");
        if (prompt == null || prompt.isEmpty()) prompt = "请你帮我解析这个pdf\n";
        userMessage.put("content",  prompt + text);

        json.put("messages", new JSONObject[]{systemMessage, userMessage});

        StringEntity entity = new StringEntity(json.toString(), StandardCharsets.UTF_8);
        postRequest.setEntity(entity);

        // 发送请求并获取响应
        HttpResponse response = httpClient.execute(postRequest);

        // 处理响应
        String responseString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        //System.out.println(responseString);
        // 解析响应中的生成内容
        JSONObject responseJson = new JSONObject(responseString);
        return responseJson.getJSONArray("choices").getJSONObject(0).getJSONObject("message").getString("content");
    }


}
